package com.atguigu.tingshu.common.minio.service.impl;

import com.atguigu.tingshu.common.minio.config.MinioProperties;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.minio.service.FileOpsService;
import com.atguigu.tingshu.common.util.MD5;
import io.minio.*;
import io.minio.errors.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

/**
 * @Author：yyj
 * @Package：com.atguigu.tingshu.album.service.impl
 * @Project：tingshu_parent240829
 * @name：FileOpsServiceImpl
 * @Date：2025/1/14 18:33
 * @Filename：FileOpsServiceImpl
 */

@Slf4j
public class FileOpsServiceImpl implements FileOpsService {
    @Autowired
    private MinioProperties minioProperties;

    @Autowired
    private MinioClient minioClient;

    @Override
    public String fileUpload(MultipartFile file) {
        String prcUrl = "";
        try {
            // 1.创建minio客户端用于和minio进行通信
//            MinioClient minioClient =
//                    MinioClient.builder()
//                            .endpoint(minioProperties.getEndpointUrl())  // minio服务器的地址在哪里
//                            .credentials(minioProperties.getAccessKey(), minioProperties.getSecreKey())
//                            .build();

            // 2.minio是否存在一个桶
//            boolean found = false;
//            found= minioClient.bucketExists(BucketExistsArgs.builder().bucket(minioProperties.getBucketName()).build());
//            if (!found) {
//
//                minioClient.makeBucket(MakeBucketArgs.builder().bucket(minioProperties.getBucketName()).build());
//            } else {
//                System.out.println("Bucket demo already exists.");
//            }
            String originalFilename = file.getOriginalFilename();

            //获取文件数据
            byte[] bytes = file.getBytes();
            //转为字符串
            String files = new String(bytes);
            //进行md5加密
            String filePrefix = MD5.encrypt(files);
            //获取文件后缀名
            String fileSuffix = originalFilename.substring(originalFilename.lastIndexOf("."), originalFilename.length());
            //加起来
            String objectName = filePrefix + fileSuffix;


            //进行校验
            StatObjectArgs.Builder statObjectArgs1 = StatObjectArgs.builder();
            StatObjectArgs statObjectArgs = statObjectArgs1.bucket(minioProperties.getBucketName())
                    .object(objectName)
                    .build();
            try {
                minioClient.statObject(statObjectArgs);// 如果不抛出异常，则代表minio指定桶中的文件已经存在，反之对象不存在
                log.info("minio指定桶中的对象存在，不用上传，直接返回对象在mino中的地址");
                return  minioProperties.getEndpointUrl() + "/" + minioProperties.getBucketName() + "/" + objectName;
            } catch (ErrorResponseException e) {
                // 上传逻辑（未来任何资源在minio眼中都就对象）
                //构建一个PutObjectArgs对象
                log.info("minio指定桶中的对象不存在，可以上传");
                PutObjectArgs.Builder builder = PutObjectArgs.builder();
                PutObjectArgs build = builder.bucket(minioProperties.getBucketName())
                        .object(objectName)
                        .stream(file.getInputStream(), file.getSize(), -1)
                        .build();
                //真正上传
                minioClient.putObject(build);
                prcUrl = minioProperties.getEndpointUrl() + "/" + minioProperties.getBucketName() + "/" + file.getOriginalFilename();
                return prcUrl;
            }
        } catch (Exception e) {
            log.info(e.getMessage());
            throw new GuiguException(201, "minio上传失败");
        }
}
}
